package cn.stylefeng.guns.modular.hx.storage.service.impl;

import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicArea;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicOperate;
import cn.stylefeng.guns.modular.basic.entity.BasicPosition;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoods;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicPositionGoods;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicPositionGoodsParam;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicPositionGoodsResult;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicPositionGoodsService;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageMoveRecord;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageOffShelf;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageStock;
import cn.stylefeng.guns.modular.hx.storage.enums.CommonVariables;
import cn.stylefeng.guns.modular.hx.storage.mapper.HxStorageOffShelfMapper;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageOffShelfParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageOutDetailedParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageStockParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageOffShelfResult;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageOutDetailedResult;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageStockResult;
import cn.stylefeng.guns.modular.hx.storage.model.result.chukuPositionResult;
import  cn.stylefeng.guns.modular.hx.storage.service.HxStorageOffShelfService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageOutDetailedService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageStockService;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 下架任务表 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-09-13
 */
@Service
public class HxStorageOffShelfServiceImpl extends ServiceImpl<HxStorageOffShelfMapper, HxStorageOffShelf> implements HxStorageOffShelfService {
    @Autowired
    private HxStorageOffShelfMapper shelfMapper;
    @Autowired
    private HxStorageOffShelfService hxStorageOffShelfService;
    @Autowired
    private HxStorageStockService stockService;
    @Autowired
    private BasicPositionService positionService;
    @Autowired
    private HxBasicPositionGoodsService positionGoodsService;
	@Resource
	private BasicAreaService basicAreaService;
    @Autowired
    private HxBasicGoodsService goodsService;

    @Autowired
    private BasicWarehouseService basicWarehouseService;

    @Autowired
    private BasicCustomerService basicCustomerService;
    @Autowired
    private BasicPositionService basicPositionService;
    @Autowired
    private HxBasicGoodsService hxBasicGoodsService;

    @Resource
    private HxStorageOutDetailedService hxStorageOutDetailedService;

    @Autowired
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;
    @Autowired
    private UserAop userAop;

    @Autowired
    private BasicOperateService basicOperateService;

    @Override
    public String addItem(HxStorageOffShelfParam param,Long id){
        //封装 HxStorageOffShelf
        HxStorageOffShelf hxStorageOffShelf = new HxStorageOffShelf();
        BeanUtils.copyProperties(param,hxStorageOffShelf);
        HxStorageStock hxStorageStock = stockService.getById(id);
        if (ToolUtil.isEmpty(hxStorageStock))
            return "error1";
        if (!"存储位".equals(hxStorageStock.getPositionType()))
            return "error3";


        BasicPosition basicPosition = new BasicPosition();
        if(hxStorageOffShelf.getPositionId() != null) {
            basicPosition = positionService.lambdaQuery()
            		.eq(BasicPosition::getWarehouseId, hxStorageStock.getWarehouseId())
            		.eq(BasicPosition::getId, hxStorageOffShelf.getPositionId())
                    .one();
        } else {
            basicPosition = positionService.lambdaQuery()
            		.eq(BasicPosition::getWarehouseId, hxStorageStock.getWarehouseId())
                    .eq(BasicPosition::getPositionNumber, hxStorageOffShelf.getPositionNumber())
                    .one();
        }
        if (ToolUtil.isEmpty(basicPosition))
            return "error2";
        if (!"拣货位".equals(basicPosition.getPositionType()))
            return "error3";
        int i = hxStorageStock.getWarehouseId().intValue();
        if (i!=basicPosition.getWarehouseId())
            return "error4";
		BasicArea basicArea = basicAreaService.getById(basicPosition.getPositionAreaId());
		//如果下架到整箱区，判断不能一位多品
		if(basicArea != null && "否".equals(basicArea.getDismantlingParts())){
			Integer count = positionGoodsService.lambdaQuery()
					.ne(HxBasicPositionGoods::getGoodsId, hxStorageStock.getGoodsId())
					.eq(HxBasicPositionGoods::getPositionId, basicPosition.getId())
					.count();
			if(count>0) {
				return "error6";
			}
		}

        LambdaQueryWrapper<HxStorageOffShelf> wrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<HxStorageOffShelf> eq = wrapper.eq(HxStorageOffShelf::getStockId, id).ne(HxStorageOffShelf::getStatus, "作废").ne(HxStorageOffShelf::getStatus, "已完成");
        HxStorageOffShelf offShelf = shelfMapper.selectOne(eq);
        if (ToolUtil.isNotEmpty(offShelf))
            return "error5";
        hxStorageOffShelf.setStatus(CommonVariables.UNCLAIMED.getDesc());
        hxStorageOffShelf.setStockId(id);
        hxStorageOffShelf.setWarehouseId(Long.valueOf(basicPosition.getWarehouseId()));
        hxStorageOffShelf.setWarehouseName(basicPosition.getWarehouseName());
        hxStorageOffShelf.setPositionId(Long.valueOf(basicPosition.getId()));
        hxStorageOffShelf.setPositionType(basicPosition.getPositionType());
        
        hxStorageOffShelf.setOldPositionId(hxStorageStock.getPositionId());
        hxStorageOffShelf.setOldPositionNumber(hxStorageStock.getPositionNumber());
        hxStorageOffShelf.setOldPositionType(hxStorageStock.getPositionType());
        hxStorageOffShelf.setTrayNumber(hxStorageStock.getTrayNumber());
        hxStorageOffShelf.setGoodsId(hxStorageStock.getGoodsId());
        hxStorageOffShelf.setGoodsName(hxStorageStock.getGoodsName());
        hxStorageOffShelf.setGoodsNumber(hxStorageStock.getGoodsNumber());
        hxStorageOffShelf.setGoodsPcode69(hxStorageStock.getGoodsPcode69());
        hxStorageOffShelf.setDetailedDate(hxStorageStock.getDetailedDate());
        hxStorageOffShelf.setKcNum(hxStorageStock.getKcNum());
        hxStorageOffShelf.setJibenNum(new BigDecimal(hxStorageStock.getKcNum()).multiply(new BigDecimal(hxStorageStock.getKcRate())));
        save(hxStorageOffShelf);
        return "ok";
    }

    @Override
    public void delete(HxStorageOffShelfParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(HxStorageOffShelfParam param){
        HxStorageOffShelf oldEntity = getOldEntity(param);
        HxStorageOffShelf newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public HxStorageOffShelfResult findBySpec(HxStorageOffShelfParam param){
        return this.baseMapper.findBySpec(param);
    }

    @Override
    public List<HxStorageOffShelfResult> findListBySpec(HxStorageOffShelfParam param){
        return null;
    }
    public List<HxStorageOffShelfResult> findOffShelfList(HxStorageOffShelf hxStorageOffShelf, String condition){
        return this.baseMapper.findOffShelfList(hxStorageOffShelf,condition);
    }

    @Override
    public LayuiPageInfo findPageBySpec(HxStorageOffShelfParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public LayuiPageInfo findOffShelfListPage(HxStorageOffShelf hxStorageOffShelf, String condition) {
        Page pageContext = getPageContext();
        IPage<HxStorageOffShelf> page = this.baseMapper.findOffShelfListPage(pageContext,hxStorageOffShelf,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public void add(HxStorageOffShelfParam hxStorageOffShelfParam) {
    	HxStorageOffShelf entity = getEntity(hxStorageOffShelfParam);
        this.save(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class,timeout = 200)
    public String offShelf(Long param,User user, BigDecimal xjNum) {
        HxStorageOffShelf offShelf = shelfMapper.selectById(param);
        if(!offShelf.getStatus().equals("已领取")) {
        	return "success";
        }
        HxStorageStock hxStorageStock = stockService.lambdaQuery()
                .eq(HxStorageStock::getId, offShelf.getStockId())
                .last(" for update ")
                .one();
        if(ToolUtil.isEmpty(hxStorageStock)){
            return "库存不存在，无法操作";
        }


        //更新下架任务表
        HxStorageOffShelf hxStorageOffShelf = new HxStorageOffShelf();
        hxStorageOffShelf.setId(param);
        hxStorageOffShelf.setStatus(CommonVariables.COMPLETED.getDesc());
        hxStorageOffShelf.setOffTime(new Date());
        shelfMapper.updateById(hxStorageOffShelf);

        if(xjNum.compareTo(BigDecimal.ZERO) == 0){
            return "success";
        }
        //更新库存表
        BasicPosition basicPosition = positionService.getById(offShelf.getPositionId());
//        BasicPosition basicPosition = positionService.lambdaQuery()
//                .eq(BasicPosition::getPositionNumber, offShelf.getPositionNumber())
//                .one();
        if(xjNum.compareTo(new BigDecimal(offShelf.getKcNum())) < 0){

            HxStorageStock addHxStorageStock = new HxStorageStock();
            ToolUtil.copyProperties(hxStorageStock,addHxStorageStock);
            addHxStorageStock.setId(null);
            addHxStorageStock.setPositionNumber(offShelf.getPositionNumber());
            addHxStorageStock.setPositionType(offShelf.getPositionType());
            addHxStorageStock.setPositionId(offShelf.getPositionId());
            addHxStorageStock.setAreaId(basicPosition.getPositionAreaId().longValue());
            addHxStorageStock.setAreaNumber(basicPosition.getAreaNumber());
            addHxStorageStock.setAreaName(basicPosition.getPositionAreaName());
            addHxStorageStock.setTransferTime(new Date());
            addHxStorageStock.setKcNum(xjNum.toString());
            addHxStorageStock.setStockVolume(String.valueOf(xjNum.multiply(new BigDecimal(hxStorageStock.getGoodsVolume()))));
            addHxStorageStock.setStockMoney(String.valueOf(xjNum.multiply(new BigDecimal(hxStorageStock.getGoodsPrice()))));
            addHxStorageStock.setStockWeight(String.valueOf(xjNum.multiply(new BigDecimal(hxStorageStock.getGoodsWeight()))));
            addHxStorageStock.setJibenNum(xjNum.multiply(new BigDecimal(hxStorageStock.getKcRate())));
            stockService.save(addHxStorageStock);
            BigDecimal syNum = new BigDecimal(hxStorageStock.getKcNum()).subtract(xjNum);
            stockService.lambdaUpdate()
                    .eq(HxStorageStock::getId, offShelf.getStockId())
                    .set(HxStorageStock::getTransferTime, new Date())
                    .set(HxStorageStock::getKcNum, syNum)
                    .set(HxStorageStock::getStockVolume, syNum.multiply(new BigDecimal(hxStorageStock.getGoodsVolume())))
                    .set(HxStorageStock::getStockMoney, syNum.multiply(new BigDecimal(hxStorageStock.getGoodsPrice())))
                    .set(HxStorageStock::getStockWeight, syNum.multiply(new BigDecimal(hxStorageStock.getGoodsWeight())))
                    .set(HxStorageStock::getStockWeight, syNum.multiply(new BigDecimal(hxStorageStock.getGoodsWeight())))
                    .set(HxStorageStock::getJibenNum, syNum.multiply(new BigDecimal(hxStorageStock.getKcRate())))
                    .update();
        }else{
            stockService.lambdaUpdate()
                    .eq(HxStorageStock::getId, offShelf.getStockId())
                    .set(HxStorageStock::getPositionNumber, offShelf.getPositionNumber())
                    .set(HxStorageStock::getPositionType, offShelf.getPositionType())
                    .set(HxStorageStock::getPositionId, offShelf.getPositionId())
                    .set(HxStorageStock::getAreaId, basicPosition.getPositionAreaId())
                    .set(HxStorageStock::getAreaNumber, basicPosition.getAreaNumber())
                    .set(HxStorageStock::getAreaName, basicPosition.getPositionAreaName())
                    .set(HxStorageStock::getTransferTime, new Date())
                    .update();
        }


        //完成库位表商品绑定
        if(basicPosition.getPositionType().equals("拣货位")) {
        	HxBasicPositionGoodsParam positionGoodsParam = new HxBasicPositionGoodsParam();
        	positionGoodsParam.setWarehouseId(Long.valueOf(basicPosition.getWarehouseId()));
        	positionGoodsParam.setPositionId(Long.valueOf(basicPosition.getId()));
        	positionGoodsParam.setGoodsId(offShelf.getGoodsId());
        	HxBasicPositionGoodsResult positionGoodsResult = positionGoodsService.findBySpec(positionGoodsParam);
        	if (ToolUtil.isEmpty(positionGoodsResult)){
        		HxBasicPositionGoods hxBasicPositionGoods = new HxBasicPositionGoods();
        		hxBasicPositionGoods.setWarehouseId(Long.valueOf(basicPosition.getWarehouseId()));
        		hxBasicPositionGoods.setAreaId(Long.valueOf(basicPosition.getPositionAreaId()));
        		hxBasicPositionGoods.setAreaName(basicPosition.getPositionAreaName());
        		hxBasicPositionGoods.setPositionId(offShelf.getPositionId());
        		hxBasicPositionGoods.setPositionNumber(offShelf.getPositionNumber());
        		hxBasicPositionGoods.setPositionPickingorder(basicPosition.getPositionPickingorder());
        		HxBasicGoods basicGoods = goodsService.getById(offShelf.getGoodsId());
        		hxBasicPositionGoods.setGoodsId(offShelf.getGoodsId());
        		hxBasicPositionGoods.setGoodsName(offShelf.getGoodsName());
        		hxBasicPositionGoods.setGoodsNumber(offShelf.getGoodsNumber());
        		hxBasicPositionGoods.setGoodsPcode69(offShelf.getGoodsPcode69());
        		hxBasicPositionGoods.setGoodsSpecs(basicGoods.getGoodsSpecs());
        		hxBasicPositionGoods.setAnquanNum(basicGoods.getAnquanNum());
        		hxBasicPositionGoods.setPsUnit(basicGoods.getPsUnit());
        		hxBasicPositionGoods.setPsRate(basicGoods.getPsRate());
        		hxBasicPositionGoods.setJibenUnit(basicGoods.getJibenUnit());
        		positionGoodsService.save(hxBasicPositionGoods);
        	}
        }

//        BasicWarehouse w = basicWarehouseService.getById(basicPosition.getWarehouseId());
//        BasicOperate byId = basicOperateService.getById(user.getOperateId());
//        BasicCustomer r = basicCustomerService.lambdaQuery()
//                .eq(BasicCustomer::getCustomerOperateId, byId.getId())
//                .last("LIMIT 1")
//                .one();
//        //System.out.println(r);
//		if(ToolUtil.isNotEmpty(r.getGsnumber())&&ToolUtil.isNotEmpty(r.getStoreIdXlb())) {
//			if(ToolUtil.isNotEmpty(r.getModeTms())&&r.getModeTms().equals("3")) {
//				if(ToolUtil.isNotEmpty(r.getXlbStorehouseId())) {
//				    BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
//				    oauth2tokenParam.setDeliverId(r.getDeliverId());
//				    oauth2tokenParam.setGsnumber(r.getGsnumber());
//				    BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
//				    //String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.movestorage.save";
//				    String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.movestorage.save";
//				    JSONArray ordersArray = new JSONArray();
//				    JSONObject orderObject = new JSONObject();
//				    BasicPosition  basicPosition1= basicPositionService.lambdaQuery()
//				            .eq(BasicPosition::getId,offShelf.getPositionId() )
//				            .last("LIMIT 1")
//				            .one();
//				    BasicPosition  basicPosition2= basicPositionService.lambdaQuery()
//				            .eq(BasicPosition::getId,offShelf.getOldPositionId() )
//				            .last("LIMIT 1")
//				            .one();
//				    HxBasicGoods  hxBasicGoods= hxBasicGoodsService.lambdaQuery()
//				            .eq(HxBasicGoods::getId,offShelf.getGoodsId() )
//				            .last("LIMIT 1")
//				            .one();
//				    HxStorageStock stock = stockService.lambdaQuery()
//				            .eq(HxStorageStock::getId, offShelf.getStockId())
//				            .last("LIMIT 1")
//				            .one();
//				    LocalDate productionDate = LocalDate.parse(stock.getDetailedDate());
//				    // 保质期（以月份表示）
//				    String shelfLifeMonths =stock.getGoodsWarranty();
//				    LocalDateTime outputDateTime = productionDate.atStartOfDay();
//
//				    // 计算到期日期
//                    LocalDate expiryDate = productionDate.plusMonths(Integer.parseInt(shelfLifeMonths));
//				    // 格式化输出到期日期
//				    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//				    LocalDateTime expiryDateTime = expiryDate.atStartOfDay();
//				    String formattedExpiryDate = expiryDateTime.format(formatter);// 格式化输出到期日期
//				    String deliveryDate = outputDateTime.format(formatter);// 格式化输出生产日期
//				    BigDecimal jibennum = new BigDecimal(offShelf.getKcNum());
//				    BigDecimal jibenrate = new BigDecimal(hxBasicGoods.getKcRate());
//				    orderObject.put("basic_quantity",jibennum.multiply(jibenrate));//基本数量
//				    orderObject.put("expire_date", formattedExpiryDate);//到期日期
//				    orderObject.put("in_storage_id", basicPosition1.getPositionXlbId());//	移入库位id 必填
//				    orderObject.put("item_code",offShelf.getGoodsNumber());//商品条码
//				    orderObject.put("item_bar_code",offShelf.getGoodsPcode69());//商品代码
//				    orderObject.put("item_id",hxBasicGoods.getGoodsXlbId());//商品id
//				    orderObject.put("item_name",offShelf.getGoodsName());//商品名称
//				    orderObject.put("item_spec",hxBasicGoods.getGoodsSpecs());//规格
//
//				    orderObject.put("producing_date",deliveryDate);//生产日期
//				    orderObject.put("quantity", offShelf.getKcNum());//数量 必填
//				    orderObject.put("ratio", hxBasicGoods.getKcRate());//换算率 必填
//				    orderObject.put("stock_detail_id", "");//库存明细id
//				    orderObject.put("storage_id",basicPosition2.getPositionXlbId());//	移出库位id 必填
//				    orderObject.put("store_id", r.getStoreIdXlb());//门店id 必填
//				    orderObject.put("storehouse_id", w.getWarehouseXlbId());//仓库id 必填
//				    orderObject.put("unit", hxBasicGoods.getKcUnit());//单位
//				//    orderObject.put("finish", 0);//单位
//				    ordersArray.put(orderObject);
//				    JSONObject json = new JSONObject();
//				    json.put("details", ordersArray);//明细
//                    json.put("operator", user.getName());//操作人
//				    String response = HttpRequest.post(url)
//							.timeout(60000)
//				            .header("Authorization", "Bearer "+oauth2tokenResult.getOauth2TokenXlb())
//				            .body(json.toString()).execute().body();
//				    JSONObject jsonObject = new JSONObject(response);
//				    if (jsonObject.get("code").toString().equals("0")) {
//				        hxStorageOffShelfService.lambdaUpdate()
//				                .set(HxStorageOffShelf::getReturnStatus, "已完成")
//				                .eq(HxStorageOffShelf::getId, offShelf.getId())
//				                .update();
//				    }else {
//				        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
//				        return "回传失败";
//			        }
//			   }
//			}
//		}
        return "success";
    }

    @Override
    public LayuiPageInfo off(HxStorageOffShelfParam hxStorageOffShelfParam, String condition) {
        Page pageContext = getPageContext();
        IPage qualityuser = this.baseMapper.offShelt(pageContext,hxStorageOffShelfParam,condition);
        return   LayuiPageFactory.createPageInfo(qualityuser);
    }

    @Override
    public List<HxStorageOffShelfResult> findxiajia(HxStorageOffShelfResult hxStorageOffShelfResult) {
        return this.baseMapper.findxiajia(hxStorageOffShelfResult);
    }

    private Serializable getKey(HxStorageOffShelfParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private HxStorageOffShelf getOldEntity(HxStorageOffShelfParam param) {
        return this.getById(getKey(param));
    }

    private HxStorageOffShelf getEntity(HxStorageOffShelfParam param) {
        HxStorageOffShelf entity = new HxStorageOffShelf();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

	@Override
	public HxStorageOffShelfResult sumOffShelf(HxStorageOffShelfParam hxStorageOffShelfParam) {
		return this.baseMapper.sumOffShelf(hxStorageOffShelfParam);
	}

	@Override
	public List<HxStorageOffShelfResult> findlistAllBySpec(HxStorageOffShelfParam hxStorageOffShelfParam,
			String condition) {
		return this.baseMapper.findlistAllBySpec(hxStorageOffShelfParam,condition);
	}

	@Override
	public HxStorageOffShelfResult count(HxStorageOffShelfParam hxStorageOffShelfParam, String condition) {
		return this.baseMapper.count(hxStorageOffShelfParam,condition);
	}

    @Override
    public int updateTaskFlag(HxStorageOffShelfParam hxStorageOffShelfParam) {
        return this.baseMapper.updateTaskFlag(hxStorageOffShelfParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class,timeout = 180)
    public void offShelfTaskJob(Long warehouseId) {

        //根据仓库ID获取仓库记录
        List<HxStorageStock> hxStorageStockList = stockService.lambdaQuery()
                .eq(HxStorageStock::getWarehouseId, warehouseId)
                .eq(HxStorageStock::getStockState, "正常")
                .eq(HxStorageStock::getPositionType,"存储位")
                .apply(" DATE_ADD(IF(IFNULL(goods_warranty,'0') = '0',CURRENT_DATE,DATE_ADD(detailed_date, INTERVAL CEIL(goods_warranty/2) DAY)),INTERVAL 10 DAY) < CURRENT_DATE ")
                .list();
        //当前库存的下架任务
        List<HxStorageOffShelf> hxStorageOffShelfList = hxStorageOffShelfService.lambdaQuery()
                .eq(HxStorageOffShelf::getWarehouseId, warehouseId)
                .notIn(HxStorageOffShelf::getStatus,"已完成","作废")
                .list();
        Map<String,Long> hxStorageOffShelfMap = new HashMap<>();
        if(hxStorageOffShelfList != null && hxStorageOffShelfList.size() > 0){
            for(HxStorageOffShelf obj : hxStorageOffShelfList){
                hxStorageOffShelfMap.put(obj.getStockId().toString(),obj.getStockId());
            }
        }

        List<HxBasicPositionGoods> positionGoodslist = positionGoodsService.lambdaQuery()
                .eq(HxBasicPositionGoods::getWarehouseId, warehouseId)
                .list();

        Map<String,HxBasicPositionGoods> positionGoodsMap = new HashMap<>();
        for(HxBasicPositionGoods obj : positionGoodslist){
            positionGoodsMap.put(obj.getGoodsId().toString(),obj);
        }

        //添加强下架库存
        if(hxStorageStockList != null && hxStorageStockList.size() > 0){
            HxStorageOffShelfParam addOffShelfParam = null;
            for(HxStorageStock obj : hxStorageStockList){
                if(hxStorageOffShelfMap.get(obj.getId().toString())!=null){
                    continue;
                }
                if(positionGoodsMap.get(obj.getGoodsId().toString())==null){
                    continue;
                }
                addOffShelfParam = new HxStorageOffShelfParam();
                addOffShelfParam.setStatus("待领取");
                addOffShelfParam.setStockId(Long.parseLong(obj.getId().toString()));
                addOffShelfParam.setWarehouseId(obj.getWarehouseId());
                addOffShelfParam.setWarehouseName(obj.getWarehouseName());
                addOffShelfParam.setPositionId(positionGoodsMap.get(obj.getGoodsId().toString()).getPositionId());
                addOffShelfParam.setPositionNumber(positionGoodsMap.get(obj.getGoodsId().toString()).getPositionNumber());
                addOffShelfParam.setPositionType("拣货位");
                addOffShelfParam.setOldPositionId(obj.getPositionId());
                addOffShelfParam.setOldPositionNumber(obj.getPositionNumber());
                addOffShelfParam.setOldPositionType(obj.getPositionType());
                addOffShelfParam.setTrayNumber(obj.getTrayNumber());
                addOffShelfParam.setGoodsId(obj.getGoodsId());
                addOffShelfParam.setGoodsName(obj.getGoodsName());
                addOffShelfParam.setGoodsNumber(obj.getGoodsNumber());
                addOffShelfParam.setGoodsPcode69(obj.getGoodsPcode69());
                addOffShelfParam.setDetailedDate(obj.getDetailedDate());
                addOffShelfParam.setKcNum(obj.getKcNum());
                addOffShelfParam.setJibenNum(obj.getJibenNum());
                addOffShelfParam.setCreateUserName("定时");
                addOffShelfParam.setDeptId(obj.getDeptId());
                addOffShelfParam.setOperateId(obj.getOperateId());
                addOffShelfParam.setTaskFlag("强");
                hxStorageOffShelfService.add(addOffShelfParam);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class,timeout = 180)
    public String safetyStockGenOffShelfTaskJob(Long warehouseId) {
        BasicWarehouse basicWarehouse = basicWarehouseService.getById(warehouseId);
        if(basicWarehouse == null){
            return "fail";
        }
        //查询拣货库位下商品库存
        List<HxStorageStockResult> hxStorageStockList = stockService.getPositionKcnum(HxStorageStockParam.builder()
                .warehouseId(warehouseId)
                .build());

        BigDecimal as = new BigDecimal(0);
        for(HxStorageStockResult obj : hxStorageStockList){
            HxBasicGoods hxBasicGoods = hxBasicGoodsService.getById(obj.getGoodsId());
            if(hxBasicGoods == null){
                continue;
            }
            BigDecimal anquanNum = new BigDecimal(0);
            if(ToolUtil.isNotEmpty(hxBasicGoods.getAnquanNum())){
                anquanNum = new BigDecimal(hxBasicGoods.getAnquanNum());
            }
            BigDecimal kcNumSumJbdw = new BigDecimal("0");
            //判断是否低于安全库存值
            if (obj != null) {
                kcNumSumJbdw = obj.getJibenNum();
            }
            HxStorageOutDetailedParam hxStorageOutDetailedParam2 = new HxStorageOutDetailedParam();
            hxStorageOutDetailedParam2.setSetWarehouseId(warehouseId);
            hxStorageOutDetailedParam2.setPositionId(obj.getPositionId());
            hxStorageOutDetailedParam2.setGoodsId(obj.getGoodsId());
            HxStorageOutDetailedResult djh = hxStorageOutDetailedService.findJhZSumBySpec(hxStorageOutDetailedParam2);//拣货中 库存
            BigDecimal djhb = new BigDecimal("0");
            if (djh != null) {
                djhb = new BigDecimal(djh.getJibenNum()).setScale(3, BigDecimal.ROUND_HALF_DOWN);//拣货中
            }
            HxStorageOffShelfParam hxStorageOffShelfParam = new HxStorageOffShelfParam();
            hxStorageOffShelfParam.setPositionId(obj.getPositionId());
            hxStorageOffShelfParam.setGoodsId(obj.getGoodsId());
            HxStorageOffShelfResult offres = hxStorageOffShelfService.sumOffShelf(hxStorageOffShelfParam);//汇总待下架
            BigDecimal dxj = new BigDecimal("0");
            if (offres != null && ToolUtil.isNotEmpty(offres.getJibenNum())) {
                dxj = offres.getJibenNum();
            }
            BigDecimal jhwKc = kcNumSumJbdw;
            BigDecimal jhzKc = kcNumSumJbdw.subtract(djhb);
            kcNumSumJbdw = kcNumSumJbdw.subtract(djhb);
            kcNumSumJbdw = kcNumSumJbdw.add(dxj);//库存-待拣货+待下架 = 实际可用库存

            //实际可用库存 小于 0  待下架和新增下架任务 急
            String taskFlag = "";

            if (jhwKc.compareTo(djhb) == -1) {
                //拣货库存小于待拣货库存， 待下架任务 急
                hxStorageOffShelfParam.setTaskFlag("急");
                hxStorageOffShelfService.updateTaskFlag(hxStorageOffShelfParam);
            }

            if (offres != null && ToolUtil.isNotEmpty(offres.getJibenNum())) {
                continue;
            }

            if (kcNumSumJbdw.compareTo(as) == -1) {
                //实际可用库存 小于0  新增下架任务 急
                taskFlag = "急";
            }

            //安全库存值，换算成基本单位
            BigDecimal anquanNumJbdw = anquanNum.multiply(new BigDecimal(hxBasicGoods.getKcRate()));
            //新增下架任务
            if (anquanNumJbdw.compareTo(jhzKc) == 1) {
                //查询库存 生产日期早的
                HxStorageStockParam OffShelfparam = new HxStorageStockParam();
                OffShelfparam.setStockState("正常");
                OffShelfparam.setWarehouseId(warehouseId);
                OffShelfparam.setPositionType("存储位");
                OffShelfparam.setGoodsId(obj.getGoodsId());
                OffShelfparam.setNotOffShelf("NotOffShelf");
                List<HxStorageStockResult> OffShelfres = stockService.findaddOffShelflist(OffShelfparam);

                for(HxStorageStockResult _obj : OffShelfres){
                    HxStorageOffShelfParam addOffShelfParam = new HxStorageOffShelfParam();
                    addOffShelfParam.setStatus("待领取");
                    addOffShelfParam.setStockId(_obj.getId().longValue());
                    addOffShelfParam.setWarehouseId(_obj.getWarehouseId());
                    addOffShelfParam.setWarehouseName(_obj.getWarehouseName());
                    addOffShelfParam.setPositionId(obj.getPositionId());
                    addOffShelfParam.setPositionNumber(obj.getPositionNumber());
                    addOffShelfParam.setPositionType("拣货位");
                    addOffShelfParam.setOldPositionId(_obj.getPositionId());
                    addOffShelfParam.setOldPositionNumber(_obj.getPositionNumber());
                    addOffShelfParam.setOldPositionType(_obj.getPositionType());
                    addOffShelfParam.setTrayNumber(_obj.getTrayNumber());
                    addOffShelfParam.setGoodsId(_obj.getGoodsId());
                    addOffShelfParam.setGoodsName(hxBasicGoods.getGoodsName());
                    addOffShelfParam.setGoodsNumber(hxBasicGoods.getGoodsNumber());
                    addOffShelfParam.setGoodsPcode69(hxBasicGoods.getGoodsPcode69());
                    addOffShelfParam.setDetailedDate(_obj.getDetailedDate());
                    addOffShelfParam.setKcNum(_obj.getKcNum());
                    addOffShelfParam.setJibenNum(_obj.getJibenNum());
                    addOffShelfParam.setCreateUserName("定时任务");
                    addOffShelfParam.setDeptId(hxBasicGoods.getDeptId());
                    addOffShelfParam.setOperateId(basicWarehouse.getWarehouseOperateId().longValue());
                    addOffShelfParam.setTaskFlag(taskFlag);
                    hxStorageOffShelfService.add(addOffShelfParam);
                    break;
//                    jhzKc = jhzKc.add(_obj.getJibenNum());
//                    if(anquanNumJbdw.compareTo(jhwKc) == -1){
//                        break;
//                    }
                }
            }
        }
        return "sucess";
    }

}
